import { login, getUserInfo, getUserDetail } from '@/api/user'
import { setToken, removeToken, getToken } from '@/utils/auth'
import router from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {} // 这里不能为null 后期要调用对象的属性 如果为null 直接报错 {}.xxx会使undefined
  },
  mutations: {
    setToken(state, value) {
      state.token = value
      setToken(value)
    },
    removeToken(state) {
      state.token = ''
      removeToken()
    },
    setUserInfo(state, value) {
      state.userInfo = value
    }
  },
  actions: {
    async actionLogin({ commit }, data) {
      const res = await login(data)
      commit('setToken', res)
    },
    async getUserInfos({ commit }) {
      const res = await getUserInfo()
      const res2 = await getUserDetail(res.userId)
      // console.log(res, '+++')
      commit('setUserInfo', { ...res, ...res2 })
    },
    // 退出登录
    logout({ commit }) {
      // 1. 删除token
      commit('removeToken')
      // 2.删除用户信息 防止下次登录拿到之前的数据
      commit('setUserInfo', {})
      // 3.跳转到登录页面
      router.push('/login')
    }
  }
}

